import wepy from 'wepy';

import tip from './tip';

export default class http {
  static async request(method = 'GET', url, data, loading = true) {
    if(wx.getStorageSync('token')){
      wepy.$instance.globalData.auth['token'] = wx.getStorageSync('token');
    }
    let params = {
      url,
      method,
      data
    };
    if (loading) {
      tip.loading();
    }
    console.info(`[http]request url=${url}`);
    const res = await wepy.request(params);
    if (loading) {
      tip.loaded();
    }
    if (url.indexOf('login')>0) {
      let data = res.data.data;
      await wx.setStorageSync('token',data.token );
      await wx.setStorageSync('key',data.key);
      await wx.setStorageSync('uname',data.uname);
      await wx.setStorageSync("userid",data.uid);
      wepy.$instance.globalData.auth['token'] = data.token;
      wepy.$instance.globalData.auth['key'] = data.key;
      wepy.$instance.globalData.auth['userid'] = data.uid;
    }
    if(this.isSuccess(res)){
      return res.data.data;
    }else {
      throw this.requestException(res);
    }
  }

  /* 判断是否成功 */
  static isSuccess(res) {
    const { statusCode } = res;
    if (!statusCode == 200) {
      return false;
    }
    if(res.data.code==0){
      return true
    }
    if(res.data.code==200){
      return true
    }
    if(res.data.code==1007){
      tip.toast(res.data.msg, null, ()=>{
        wx.redirectTo({
          url: '/pages/mine/bindPhone'
        })
      });
      return false
    }
    if(res.data.code==1003){
      tip.toast(res.data.msg, null, ()=>{
        wx.redirectTo({
          url: '/pages/mine/bindPhone'
        })
      });
      return false
    }
    if(res.data.code==500){
      tip.toast(res.data.msg, null, ()=>{
      });
      return false
    }

  }

  /*  异常处理 */
  static requestException(res){
    const error = {};
    if(res.statusCode !== 200){
      error.statusCode = res.statusCode;
      error.msg = res.resultMessage;
      return error;
    }else {
      error.status = res.data.status;
      error.msg=res.data.msg;
    }
  }
  /*
  * http 封装
  * */

  static get (url,data,loading=true){
    return this.request('GET',url,data,loading);
  }
  static post (url,data,loading=true){
    return this.request('POST',url,data,loading);
  }
  static put (url,data,loading=true){
    return this.request('PUT',url,data,loading);
  }
  static patch (url,data,loading=true){
    return this.request('PATCH',url,data,loading);
  }
  static delete (url,data,loading=true){
    return this.request('DELETE',url,data,loading);
  }


}

